package com.cicadasmall.initializer.plugin;

import com.cicadasmall.plugin.annotation.Plugin;
import com.cicadasmall.common.func.Fn;
import com.cicadasmall.plugin.IPlugin;
import com.cicadasmall.common.utils.SpringContextUtils;
import com.cicadasmall.plugin.manager.PluginsManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 插件初始化
 *
 * @author Jin
 */
@Slf4j
@Component
@Configuration
public class PluginInitializer implements CommandLineRunner {

    @Autowired
    private PluginsManager pluginsManager;

    public void loadPlugin() {
        Map<String, Object> pluginMap = SpringContextUtils.getBeansWithAnnotation(Plugin.class);
        if (Fn.isNotNull(pluginMap)) {
            pluginMap.forEach((key, value) -> {
                pluginsManager.registerPlugin((IPlugin) value);
                log.info("注册插件 - {}", key);
            });
        }
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("========[ 开始注册插件]========");
        this.loadPlugin();
        log.info("========[ 插件注册完成 ]========\n");
    }
}
